package com.im.web.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;

import com.taotao.shiro.ShiroDBRealm;

public class ShiroSessionTimeoutFilter extends PathMatchingFilter {
	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			Session session = subject.getSession(false);
			if (session != null) {
				Object attribute = session.getAttribute(ShiroDBRealm.SESSION_USER_KEY);
				if (attribute == null) {
					if ("XMLHttpRequest"
							.equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
						// ajax的sesson处理
						// 返回状态码
						System.out.println("session过期");
						onLoginFail(response);
						return false;
					}
				}
			}
		}
		return true;
	}

	// session过期给403状态码
	private void onLoginFail(ServletResponse response) throws IOException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setStatus(403);
		httpResponse.getWriter().write("session超时了");
	}
}
